//
//  ReadViewController.m
//  口袋
//
//  Created by dllo on 15/5/21.
//  Copyright (c) 2015年 口袋. All rights reserved.
//

#import "ReadViewController.h"
#import "ReadTableViewCell.h"
#import "MyOrderViewController.h"
#import "MyRecommendViewController.h"
#import "Type1ViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "SANetWorkingTask.h"
#import "ReadModel.h"
#import "ThreePictureCell.h"
#import "OneBigPicCell.h"
#import "OneBigPicViewController.h"
#import "ThreePicViewController.h"
#import <MJRefresh.h>
#import "Reachability.h"
@interface ReadViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, retain)UIScrollView *scroll;
@property (nonatomic, retain)UISegmentedControl *segment;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)MyRecommendViewController *recommend;
@property (nonatomic, retain)NSMutableArray *array;
@property (nonatomic, assign)NSInteger a;
@property (nonatomic, retain)ReadModel *model;
@end

@implementation ReadViewController
- (void)dealloc
{
    [_segment release];
    [_scroll release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        [SANetWorkingTask request:@" http://c.3g.163.com/recommend/getSubDocPic?passport=&devId=7206683F-9E5B-4BC9-9940-3EBBEC6DF8B9&size=6&from=yuedu" parmater:nil block:^(NSDictionary *result) {
            NSArray *arr = [result objectForKey:@"推荐"];
            for (NSDictionary *dic in arr) {
                self.model = [[ReadModel alloc]init];
                [_model setValuesForKeysWithDictionary:dic];
                [self.array addObject:_model];
            }
            [self createTableView];
        }];
    }
    return self;
}

#pragma mark -
#pragma mark 创建基础样式

- (void)createSeg
{
    self.segment = [[UISegmentedControl alloc]initWithItems:@[@"推荐阅读"]];
    [self.segment setFrame:CGRectMake(95, 10, 200, 30)];
    self.segment.tintColor = [UIColor whiteColor];
    _segment.selectedSegmentIndex = 0;
    [self.navigationController.navigationBar addSubview:self.segment];
    [_segment addTarget:self action:@selector(segmentClicked:) forControlEvents:(UIControlEventValueChanged)];
    [self.segment release];
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x == 0) {
        self.segment.selectedSegmentIndex = 0;
    } else if (scrollView.contentOffset.x == self.view.frame.size.width) {
        self.segment.selectedSegmentIndex = 1;
    }
}
- (void)segmentClicked:(UISegmentedControl *)seg
{
    switch (seg.selectedSegmentIndex) {
        case 0:
        {
            [self.scroll setContentOffset:CGPointMake(0, 0)];
        }
            break;
        case 1:
        {
            [self.scroll setContentOffset:CGPointMake(self.view.frame.size.width, 0)];
        }
            break;
    }
}
- (void)createScrollView
{
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.scroll.contentSize = CGSizeMake(self.view.frame.size.width , self.view.frame.size.height - 110);
    self.scroll.delegate = self;
    _scroll.pagingEnabled = YES;
    [self.view addSubview:_scroll];
    MyOrderViewController *order = [[MyOrderViewController alloc] initWithNibName:nil bundle:nil];
    [_scroll addSubview:order.view];
    
    
    
    [order release];
    self.recommend = [[MyRecommendViewController alloc] initWithNibName:nil bundle:nil];
    [_scroll addSubview:_recommend.view];
    [_recommend release];
    [_scroll release];
}
#pragma mark -
#pragma mark 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height- 110)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.recommend.view addSubview:self.tableView];
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(Refresh)];
    [self.tableView.header beginRefreshing];
    [self.tableView setSeparatorColor:[UIColor colorWithRed:128/255.0 green:217/255.0 blue:215/255.0 alpha:1.0]];
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(Load)];
    self.tableView.footer.automaticallyRefresh = NO;
    [self.tableView release];
}
- (void)Refresh
{
    
    self.tableView.userInteractionEnabled = NO;
    
    self.array = [NSMutableArray array];
    [SANetWorkingTask request:@"http://c.3g.163.com/recommend/getSubDocPic?passport=&devId=7206683F-9E5B-4BC9-9940-3EBBEC6DF8B9&size=20&from=yuedu" parmater:nil block:^(NSDictionary *result) {
        NSArray *arr = [result objectForKey:@"推荐"];
        for (NSDictionary *dic in arr) {
            self.model = [[ReadModel alloc]init];
            [_model setValuesForKeysWithDictionary:dic];
            [self.array addObject:_model];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        self.tableView.userInteractionEnabled = YES;
    }];
    
   
}
- (void)Load
{
    self.tableView.userInteractionEnabled = NO;
    [SANetWorkingTask request:@"http://c.3g.163.com/recommend/getSubDocPic?passport=&devId=7206683F-9E5B-4BC9-9940-3EBBEC6DF8B9&size=20&from=yuedu" parmater:nil block:^(NSDictionary *result) {
        NSArray *arr = [result objectForKey:@"推荐"];
        for (NSDictionary *dic in arr) {
            self.model = [[ReadModel alloc]init];
            [_model setValuesForKeysWithDictionary:dic];
            [self.array addObject:_model];
        }
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
            self.tableView.userInteractionEnabled = YES;
    }];

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count - 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReadModel *model = [self.array objectAtIndex:indexPath.row + 1];
    if ([model.Template isEqualToString:@"normal"]) {
        static NSString *cellIdentify = @"cell";
        ReadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        if (!cell) {
            cell = [[ReadTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify];
        }
        
        
        [cell.showImage sd_setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
        cell.title.text = model.title;
        cell.title.numberOfLines = 0;
        cell.digest.text = model.digest;
        cell.digest.numberOfLines = 0;
        cell.digest.font = [UIFont fontWithName:nil size:13];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if ([model.Template isEqualToString:@"pic31"]){
        
    static NSString *pic3cell = @"three";
    //用数组类型的属性取到model下一层的数组imgnewextra
    ThreePictureCell *cell = [tableView dequeueReusableCellWithIdentifier:pic3cell];
    if (!cell) {
        cell = [[ThreePictureCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:pic3cell];
    }
        [cell.firstImageView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
                 NSDictionary *dic = [model.imgnewextra objectAtIndex:0];
        [cell.secondImageView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"imgsrc"]] placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
            NSDictionary *dic1 = [model.imgnewextra objectAtIndex:1];
        [cell.thirdImageView sd_setImageWithURL:[NSURL URLWithString:[dic1 objectForKey:@"imgsrc"]] placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
        cell.title.text = model.title;
        cell.digest.text = model.digest;
        cell.digest.numberOfLines = 0;
        cell.digest.font = [UIFont fontWithName:nil size:13];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    static NSString * oneCell = @"one";
    OneBigPicCell *cell = [tableView dequeueReusableCellWithIdentifier:oneCell];
    if (!cell) {
        cell = [[OneBigPicCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:oneCell];
    }
    [cell.bigImageView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
    cell.title.text = model.title;
    cell.digest.text = model.digest;
    //设置cell字体 自动换行
    cell.digest.font = [UIFont fontWithName:nil size:13];
    cell.digest.numberOfLines = 0;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ReadModel *model = [self.array objectAtIndex:indexPath.row + 1];
    if([model.Template isEqualToString:@"normal"]){
    return [UIScreen mainScreen].bounds.size.height * 0.2;
    } else if ([model.Template isEqualToString:@"pic31"]){
    return [UIScreen mainScreen].bounds.size.height * 0.42;
    }
    return [UIScreen mainScreen].bounds.size.height * 0.45;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReadModel *model = [self.array objectAtIndex:indexPath.row + 1];
    Type1ViewController *type1 = [[Type1ViewController alloc]init];
        type1.str = model.docid;
    [self.navigationController pushViewController:type1 animated:YES];
    [type1 release];

}

- (void)loadView
{
    [super loadView];
//    [self createSeg];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    [self createScrollView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor greenColor]];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:128/255.0 green:217/255.0 blue:215/255.0 alpha:1.0]];
//    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"推荐阅读1.png"] forBarMetrics:UIBarMetricsDefault];
    [self isConnectionAvailable];
    //self.navigationItem.title = @"推荐阅读";
}
// 判断网络连接
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            NSLog(@"没网");
            [self alertView:@"没有网络连接"];
            [self.tableView.header endRefreshing];
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            NSLog(@"用的WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            NSLog(@"3G");
            [self alertView:@"使用3G连接"];
            break;
    }
    
    
    return isExistenceNetwork;
}
// 警告框
- (void)alertView:(NSString *)str
{
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
    [alert setDelegate:self];
    [alert show];
    [alert release];
    
}
@end

